﻿// -----------------------------------------------------------------------
//  <copyright file="SignalRLogger.cs" company="Hcf开源团队">
//      Copyright (c) 2017-2020 Hcf. All rights reserved.
//  </copyright>
//  <site>http://www.hcfrm.com</site>
//  <last-editor>Lemon</last-editor>
//  <last-date>2020/10/7 21:08:48</last-date>
// -----------------------------------------------------------------------

using System;
using System.Text;
using Hcf.Logger.SignalR.Hubs;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Client;

namespace Hcf.Logger.SignalR.Logger
{
    public class SignalRLogger:ILogger
    {
        private readonly SignalRConfiguration _config;
        private readonly string _categoryName;
        private readonly IHubContext<DataHub> _hubContext;
        public SignalRLogger(SignalRConfiguration signalRConfiguration,
            IHubContext<DataHub> hubContext,
            string categoryName)
        {
            _config = signalRConfiguration;
            _categoryName = categoryName;
            _hubContext = hubContext;
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return null;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return logLevel >= _config.LogLevel;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
            Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel)) return;

            StringBuilder message = new StringBuilder();
            message.Append(_categoryName);
            message.AppendFormat("[{0}]", eventId);
            message.Append(Environment.NewLine);
            message.Append(formatter(state, exception));

            _hubContext.Clients.All.SendAsync("ReceiveMessage", logLevel.ToString(), message.ToString());
        }
    }
}
